# -*- coding: utf-8 -*-            
# @Time : 2024/9/14 10:04
# @FileName: analyze-backup.py
# @Target:

def first_label_requests(content, type):
    if type == 'clarify':
        return content_requests(
            content
        )
    elif type == 'purchase':
        return content_requests(
            content
        )
    elif type == 'quality':
        return content_requests(
            content
        )
    elif type == 'csp':
        return content_requests(
            content
        )
    elif type == 'feel':
        return content_requests(
            content
        )
    else:
        logging.info("ERROR : analyze first_label_requests error")


def second_label_requests(content,
                          type,
                          first_label,
                          labels):
    if type == 'quality':
        return content_requests(
            prompt._quality_2_prompt(
                customer_voice=content,
                first_label=first_label,
                labels=labels
            )
        )
    elif type == 'csp':
        return content_requests(
            prompt._csp_2_prompt(
                customer_voice=content,
                first_label=first_label,
                labels=labels
            )
        )
    else:
        raise RuntimeError('second_label_requests')


def request_content_list(content, label):
    return content_requests(
        prompt._ner_prompt(
            customer_voice=content,
            labels=label
        )
    )


def request_sentiment(content, label):
    return content_requests(
        prompt._sentiment_prompt(
            customer_voice=content,
            content=label
        )
    )


def label_requests(init_voices, type):
    # 摘取客户的原始反馈
    customer_voice = init_voices['customer_voice']

    if type == 'convert_voice':
        return init_voices['customer_voice']
    elif type == 'clarify':
        """
        判断用户反馈是否和车辆相关
        """
        return first_label_requests(
            content=init_voices['clarify_prompt'],
            type='clarify'
        )
    elif type == 'purchase':
        """
        判断客户购买意愿
        """
        return first_label_requests(
            content=init_voices['purchase_prompt'],
            type='purchase'
        )
    elif type == 'quality':
        """
        判断客户反馈和车辆质量相关的投诉内容
        """
        first_label_list = first_label_requests(
            content=init_voices['quality_1_prompt'],
            type='quality'
        )
        if '客户反馈不在当前标签列表范围内' in first_label_list:
            first_label_list.remove('客户反馈不在当前标签列表范围内')
        #
        if len(first_label_list):
            res_labels = {_: [] for _ in first_label_list}
        else:
            res_labels = {}
            return res_labels
        for first_label in first_label_list:
            p_labels = deepcopy(labels_obj.quality_labels[first_label])
            if '客户反馈不在当前标签列表范围内' not in p_labels:
                p_labels.append('客户反馈不在当前标签列表范围内')
            second_label_list = second_label_requests(
                content=customer_voice,
                type='quality',
                first_label=first_label,
                labels=p_labels
            )
            if '客户反馈不在当前标签列表范围内' in second_label_list:
                second_label_list.remove('客户反馈不在当前标签列表范围内')
            for second_label in second_label_list:
                #
                res_labels[first_label].append({second_label: {
                    'content_list': [],
                    'sentiment': ''}}
                )
                content_list = request_content_list(
                    content=customer_voice,
                    label=first_label + '-' + second_label,
                )
                res_labels[first_label][-1][second_label]['content_list'] = content_list
                sentiment_list = request_sentiment(
                    content=customer_voice,
                    label=first_label + '-' + second_label,
                )
                if len(sentiment_list) == 0:
                    sentiment_list = ['中性情感']
                elif len(sentiment_list) > 1:
                    logging.info('ERROR ---> sentiment analysis failure')
                    sentiment_list = sentiment_list[0]
                else:
                    sentiment_list = sentiment_list[0]
                res_labels[first_label][-1][second_label]['sentiment'] = sentiment_list
        return res_labels

    elif type == 'csp':
        """
        分析客户 CSP 相关的标签
        """
        first_label_list = first_label_requests(
            content=init_voices['csp_1_prompt'],
            type='csp'
        )
        if '客户反馈不在当前标签列表范围内' in first_label_list:
            first_label_list.remove('客户反馈不在当前标签列表范围内')
        #
        if len(first_label_list):
            res_labels = {_: [] for _ in first_label_list}
        else:
            res_labels = {}
            return res_labels
        for first_label in first_label_list:
            p_labels = deepcopy(labels_obj.csp_labels[first_label])
            #
            p_labels = list(p_labels.keys())
            if '客户反馈不在当前标签列表范围内' not in p_labels:
                p_labels.append('客户反馈不在当前标签列表范围内')
            second_label_list = second_label_requests(
                content=customer_voice,
                type='csp',
                first_label=first_label,
                labels=p_labels
            )
            if '客户反馈不在当前标签列表范围内' in second_label_list:
                second_label_list.remove('客户反馈不在当前标签列表范围内')
            for second_label in second_label_list:
                #
                res_labels[first_label].append({second_label: {
                    'content_list': [],
                    'sentiment': ''}}
                )
                content_list = request_content_list(
                    content=customer_voice,
                    label=first_label + '-' + second_label,
                )
                res_labels[first_label][-1][second_label]['content_list'] = content_list
                sentiment_list = request_sentiment(
                    content=customer_voice,
                    label=first_label + '-' + second_label,
                )
                if len(sentiment_list) == 0:
                    sentiment_list = ['中性情感']
                elif len(sentiment_list) > 1:
                    logging.info('ERROR ---> sentiment analysis failure')
                    sentiment_list = sentiment_list[0]
                else:
                    sentiment_list = sentiment_list[0]
                res_labels[first_label][-1][second_label]['sentiment'] = sentiment_list
        return res_labels

    elif type == 'feel':
        """
        分析客户 FEEL 相关的标签
        """
        first_label_list = first_label_requests(
            content=init_voices['feel_1_prompt'],
            type='feel'
        )
        if '客户反馈不在当前标签列表范围内' in first_label_list:
            first_label_list.remove('客户反馈不在当前标签列表范围内')
        #
        if len(first_label_list):
            res_labels = {_: [
                {
                    'content_list': [],
                    'sentiment': ''
                }
            ] for _ in first_label_list}
        else:
            res_labels = {}
            return res_labels
        for first_label in first_label_list:
            content_list = request_content_list(
                content=customer_voice,
                label=first_label,
            )
            res_labels[first_label][-1]['content_list'] = content_list
            sentiment_list = request_sentiment(
                content=customer_voice,
                label=first_label,
            )
            if len(sentiment_list) == 0:
                sentiment_list = ['中性情感']
            elif len(sentiment_list) > 1:
                logging.info('ERROR ---> sentiment analysis failure')
                sentiment_list = sentiment_list[0]
            else:
                sentiment_list = sentiment_list[0]
            res_labels[first_label][-1]['sentiment'] = sentiment_list
        return res_labels


def callback(sentence):
    res_data = {
        'customer_voice': '',
        'clarify': '',
        'purchase': '',
        'quality_label': '',
        'csp_label': '',
        'feel_label': '',
    }

    # 将对应的客户投诉进行一次初步标签处理
    init_voices = prompt.init_preprocess_labels(
        customer_voice=sentence
    )

    # 1. 将客户的原始投诉语句，去除空格等之后装入返回字典
    res_data['customer_voice'] = label_requests(
        init_voices=init_voices,
        type='convert_voice'
    )

    # 2. 判断客户反馈是否和车辆相关
    res_data['clarify'] = label_requests(
        init_voices=init_voices,
        type='clarify'
    )

    # 3. 判断客户购买意愿
    #
    res_data['purchase'] = label_requests(
        init_voices=init_voices,
        type='purchase'
    )

    # 4. 判断客户质量相关
    res_data['quality_label'] = label_requests(
        init_voices=init_voices,
        type='quality'
    )

    # 5. 判断客户CSP相关
    res_data['csp_label'] = label_requests(
        init_voices=init_voices,
        type='csp'
    )

    # 6. 判断客户使用感受相关
    res_data['feel_label'] = label_requests(
        init_voices=init_voices,
        type='feel'
    )

    logging.info('Fianl Result ->  ', str(res_data))
    return res_data


if __name__ == '__main__':
    sentence = """

  """
    print(len(sentence))

    import json, codecs, time, os
    from pprint import pprint
    from tqdm import tqdm

    start_time = time.time()
    res_data = callback(sentence=sentence[:5000])

    print("============")
    pprint(res_data)
    end_time = time.time()

    print("Processing Time ", end_time - start_time)
    print("============")

'''
def merge_dicts(d1, d2):
    # 对于极长的文本，待探索
    for key in d2:
        if key in d1:
            if isinstance(d1[key], dict) and isinstance(d2[key], dict):
                merge_dicts(d1[key], d2[key])
            elif isinstance(d1[key], list) and isinstance(d2[key], list):
                d1[key].extend(d2[key])
            else:
                d1[key] = d2[key]
        else:
            d1[key] = d2[key]
    return d1


   # import json, codecs, time, os
    # from pprint import pprint
    # from tqdm import tqdm
    # new_data = []
    # # TODO : 可能这种大模型自己部署时候会出各种各样的问题，还是直接调llama_factory上面对应的接口吧，远程的调
    # with codecs.open(filename='data/20240825.json', mode='r', encoding='utf-8') as fr:
    #     data = json.load(fr)
    # for d in tqdm(data):
    #     content = d['content'][:1000].replace("\n", "").replace("\r", "").replace("  ", "")
    #     if len(content)<10:
    #         continue
    #     start_time = time.time()
    #     try:
    #         res_data = callback(content)
    #     except:
    #         res_data = {}
    #     end_time = time.time()
    #
    #     d.update({'res' : res_data})
    #     new_data.append(d)
    #     print("=================")
    #     pprint(res_data)
    #     print("Processing Time ", end_time - start_time)
    #     print("=================")
    # with codecs.open(filename='data/20240825-2.json', mode='w', encoding='utf-8') as fw:
    #     json.dump(obj=new_data, fp=fw, ensure_ascii=False, indent=4)
    #
    #

'''
